package com.example.javapracticaltraining.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.javapracticaltraining.entity.R;
import com.example.javapracticaltraining.entity.dto.ElderProfile;
import com.example.javapracticaltraining.entity.dto.HealthData;
import com.example.javapracticaltraining.entity.dto.HealthReport;
import com.example.javapracticaltraining.entity.pojo.AiHealthWarning;
import com.example.javapracticaltraining.entity.pojo.AiSuggestion;
import com.example.javapracticaltraining.entity.pojo.CareLevel;
import com.example.javapracticaltraining.entity.pojo.ElderlyDietNeed;
import com.example.javapracticaltraining.service.AiHealthReportService;
import com.example.javapracticaltraining.service.AiSuggestionService;
import com.example.javapracticaltraining.service.CareLevelService;
import com.example.javapracticaltraining.service.ElderlyDietNeedService;
import com.example.javapracticaltraining.service.SmartHealthService;
import com.example.javapracticaltraining.utils.ChatUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Tag(name = "AI智能服务", description = "提供AI聊天、健康风险分析、个性化护理建议和健康报告生成等功能")
@RestController
@RequestMapping("/ai")
public class AiController {

	@Autowired
	SmartHealthService smartHealthService;

	@Autowired
	CareLevelService careLevelService;

	@Autowired
	ElderlyDietNeedService elderlyDietNeedService;

	@Autowired
	AiSuggestionService aiSuggestionService;

	@Autowired
	ChatUtil chatUtil;

	@Autowired
	AiHealthReportService aiHealthReportService;


	/**
	 * 获取个性化护理建议
	 * @param elderlyId 老人ID
	 * @return 个性化护理建议
	 */
	@Operation(summary = "获取个性化护理建议", description = "获取数据库中的个性化护理建议，若不存在则ai生成写入数据库中")
	@ApiResponses(value = {
			@ApiResponse(responseCode = "200", description = "成功获取护理建议"),
			@ApiResponse(responseCode = "404", description = "未找到该老人的健康数据")
	})
	@GetMapping("/suggestion/{elderlyId}")
	public R<String> getSuggestion(
			@Parameter(description = "老人ID", required = true) @PathVariable Integer elderlyId) {
		if(aiSuggestionService.getById(elderlyId) != null) {
			return R.success(aiSuggestionService.getById(elderlyId).getSuggestion());
		}
		return generateCarePlan(elderlyId);
	}



	@Operation(summary = "AI健康问答", description = "提供基于AI的健康相关问题解答")
	@ApiResponses(value = {
		@ApiResponse(responseCode = "200", description = "返回AI回答内容")
	})
	@GetMapping("/chat")
	public R<String> chat(
		@Parameter(description = "用户提问内容") String message,
		@Parameter(description = "用户ID", required = true) int userId) {
		return R.success(smartHealthService.healthQnA(userId, message));
	}

	@Operation(summary = "健康风险分析", description = "分析并返回所有老人的健康风险警告")
	@ApiResponses(value = {
		@ApiResponse(responseCode = "200", description = "返回健康风险警告列表")
	})
	@GetMapping("/healthrisks")
	public R<List<AiHealthWarning>> health() {
		List<AiHealthWarning> aiHealthWarnings = smartHealthService.analyzeHealthRisks();
		return R.success(aiHealthWarnings);
	}

	/**
	 * 个性化护理建议生成
	 * @param elderlyId 老人ID
	 * @return 个性化护理建议
	 */
	@Operation(summary = "生成个性化护理建议", description = "根据老人的健康数据、护理等级和膳食需求生成个性化护理建议")
	@ApiResponses(value = {
		@ApiResponse(responseCode = "200", description = "成功生成护理建议"),
		@ApiResponse(responseCode = "404", description = "未找到该老人的健康数据")
	})
	@GetMapping("/careplan/{elderlyId}")
	public R<String> generateCarePlan(
		@Parameter(description = "老人ID", required = true) @PathVariable Integer elderlyId) {
		// 获取老人健康数据
		HealthData healthData = smartHealthService.getElderlyHealthData(elderlyId);
		if (healthData == null) {
			return R.failure(404, "未找到该老人的健康数据");
		}

		// 获取老人护理等级
		CareLevel careLevel = null;
		if (healthData.getLevelName() != null) {
			LambdaQueryWrapper<CareLevel> careLevelQuery = new LambdaQueryWrapper<>();
			careLevelQuery.eq(CareLevel::getLevelName, healthData.getLevelName());
			careLevel = careLevelService.getOne(careLevelQuery);
		}

		// 获取老人膳食需求
		LambdaQueryWrapper<ElderlyDietNeed> dietNeedQuery = new LambdaQueryWrapper<>();
		dietNeedQuery.eq(ElderlyDietNeed::getElderlyId, elderlyId);
		ElderlyDietNeed dietNeed = elderlyDietNeedService.getOne(dietNeedQuery);

		// 构建老人档案
		ElderProfile elderProfile = new ElderProfile();
		elderProfile.setElderlyId(elderlyId);
		elderProfile.setName(healthData.getName());
		elderProfile.setGender(healthData.getGender());
		elderProfile.setAge(healthData.getAge());
		elderProfile.setCareLevel(careLevel);
		elderProfile.setDietNeed(dietNeed);
		elderProfile.setHealthRecords(healthData.getHealthRecords());
		elderProfile.setMedicalRecords(healthData.getMedicalRecords());
		elderProfile.setNursingRecords(healthData.getNursingRecords());
		StringBuilder message = new StringBuilder();
		message.append("病人姓名：").append(elderProfile.getName()).append("\n");
		message.append("病人性别：").append(elderProfile.getGender()).append("\n");
		message.append("病人年龄：").append(elderProfile.getAge()).append("\n");
		message.append("病人护理等级：").append(elderProfile.getCareLevel().getLevelName()).append("\n");
		message.append("--------------------------------------------------------------").append("\n");
		message.append("个性化护理建议：").append("\n");
		message.append(smartHealthService.generatePersonalizedCarePlan(elderProfile));
		AiSuggestion aiSuggestion = new AiSuggestion();
		aiSuggestion.setElderlyId(elderProfile.getElderlyId());
		aiSuggestion.setSuggestion(message.toString());
		aiSuggestionService.saveOrUpdate(aiSuggestion);
		return new R<>(200, message.toString(), "请求成功");
	}

	/**
	 * 自动化健康报告生成
	 * @param elderlyId 老人ID
	 * @param reportType 报告类型（daily, weekly, monthly）
	 * @param targetRole 目标接收者角色（family, doctor）
	 * @return 健康报告
	 */
	@Operation(summary = "生成健康报告", description = "根据老人ID生成自动化健康报告，可指定报告类型和目标接收者角色")
	@ApiResponses(value = {
		@ApiResponse(responseCode = "200", description = "成功生成健康报告"),
		@ApiResponse(responseCode = "404", description = "未找到该老人的健康数据")
	})
	@GetMapping("/healthreports/{elderlyId}")
	public R<HealthReport> generateHealthReport(
			@Parameter(description = "老人ID", required = true) @PathVariable Integer elderlyId,
			@Parameter(description = "报告类型：daily(每日)、weekly(每周)、monthly(每月)，默认为daily", example = "daily") String reportType,
			@Parameter(description = "目标接收者角色：family(家属)、doctor(医生)，默认为family", example = "family") String targetRole) {

		// 验证参数
		if (reportType == null || reportType.isEmpty()) {
			reportType = "daily"; // 默认为每日报告
		}

		if (targetRole == null || targetRole.isEmpty()) {
			targetRole = "family"; // 默认为家属视角
		}

		// 生成健康报告
		HealthReport healthReport = smartHealthService.generateHealthReport(elderlyId, reportType, targetRole);

		if (healthReport == null) {
			return R.failure(404, "未找到该老人的健康数据");
		}

		// 保存健康报告到数据库
		aiHealthReportService.saveHealthReport(healthReport, targetRole);

		return R.success(healthReport);
	}
}
